<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 一,普通数组扁平化(先把数组以逗号形式转为字符串,然后再转为数组,然后通过map返回新数组的特性强制返回一个整形)
      // let arr = [1, 2, [3, 4, [5, 7, [8, [9]]]]];
      // const A = arr.join(",").split(",").map(item=>item)
      // console.log(A);

      // 二,对象数组扁平化(使用递归)
      let lonArr = [
        {
          name: "张三1",
          children: [
            { name: "张三2" },
            {
              name: "张三3",
              children: [{ name: "张三4" }],
            },
          ],
        },
        {
          name: "张三5",
          children: [
            { name: "张三6" },
            {
              name: "张三7",
              children: [{ name: "张三8" }],
            },
          ],
        },
        {
          name: "张三9",
          children: [
            { name: "张三10" },
            {
              name: "张三11",
              children: [{ name: "张三12" }],
            },
          ],
        },
      ];
        // 第一种扁平方法
      let newArr = [];
      function fun(lonArr) {
        // 01.遍历传递进来的数组
        lonArr.forEach((item, index) => {
          // 02.把数据每次都push进新的数组中
          newArr.push(item);
          // 03.判断每一次遍历的数据是否存在数组,这边模拟的一个数据的子数组是children
          if (item.children) {
            // 04.如果是数组的话就重新调用自己进行push的操作
            fun(item.children);
          }
        });
        return newArr;
      }
      console.log(fun(lonArr));

        // 第二种扁平方法
       function tranTreeToList(list) {
        let arr = [];
        list.forEach((item) => {
          arr.push(item);
          if (item.children && item.children.length) {
            arr = arr.concat(tranTreeToList(item.children));
          }
        });
        return arr;
      }
      console.log(tranTreeToList(lonArr));
      
    </script>
  </body>
</html>
